import '../models/essay_material.dart';
import '../services/web_database_service.dart';

class EssayMaterialRepository {
  final WebDatabaseService _dbService = WebDatabaseService();
  static const String _tableName = WebDatabaseService.essayMaterialsTable;

  /// 添加作文素材
  Future<int> addEssayMaterial(EssayMaterial material) async {
    final data = material.toMap();
    data.remove('id'); // 移除id，让数据库自动生成
    return await _dbService.insert(_tableName, data);
  }

  /// 获取所有作文素材
  Future<List<EssayMaterial>> getAllEssayMaterials() async {
    final results = await _dbService.getAll(_tableName);
    return results.map((data) => EssayMaterial.fromMap(data)).toList();
  }

  /// 根据ID获取作文素材
  Future<EssayMaterial?> getEssayMaterialById(int id) async {
    final result = await _dbService.getById(_tableName, id);
    return result != null ? EssayMaterial.fromMap(result) : null;
  }

  /// 根据分类获取作文素材
  Future<List<EssayMaterial>> getEssayMaterialsByCategory(String category) async {
    final results = await _dbService.getByIndex(_tableName, 'category', category);
    return results.map((data) => EssayMaterial.fromMap(data)).toList();
  }

  /// 搜索作文素材
  Future<List<EssayMaterial>> searchEssayMaterials(String keyword) async {
    final allMaterials = await getAllEssayMaterials();
    return allMaterials.where((material) => 
      material.title.toLowerCase().contains(keyword.toLowerCase()) ||
      material.content.toLowerCase().contains(keyword.toLowerCase()) ||
      material.source.toLowerCase().contains(keyword.toLowerCase())
    ).toList();
  }

  /// 根据标签搜索作文素材
  Future<List<EssayMaterial>> getEssayMaterialsByTag(String tag) async {
    final allMaterials = await getAllEssayMaterials();
    return allMaterials.where((material) => 
      material.tags.toLowerCase().contains(tag.toLowerCase())
    ).toList();
  }

  /// 根据来源获取作文素材
  Future<List<EssayMaterial>> getEssayMaterialsBySource(String source) async {
    final allMaterials = await getAllEssayMaterials();
    return allMaterials.where((material) => 
      material.source.toLowerCase().contains(source.toLowerCase())
    ).toList();
  }

  /// 获取最近创建的作文素材
  Future<List<EssayMaterial>> getRecentEssayMaterials(int count) async {
    final allMaterials = await getAllEssayMaterials();
    allMaterials.sort((a, b) => b.createdAt.compareTo(a.createdAt));
    return allMaterials.take(count).toList();
  }

  /// 获取最近更新的作文素材
  Future<List<EssayMaterial>> getRecentlyUpdatedEssayMaterials(int count) async {
    final allMaterials = await getAllEssayMaterials();
    allMaterials.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
    return allMaterials.take(count).toList();
  }

  /// 随机获取作文素材
  Future<List<EssayMaterial>> getRandomEssayMaterials(int count, {String? category}) async {
    List<EssayMaterial> materials;
    
    if (category != null) {
      materials = await getEssayMaterialsByCategory(category);
    } else {
      materials = await getAllEssayMaterials();
    }
    
    materials.shuffle();
    return materials.take(count).toList();
  }

  /// 更新作文素材
  Future<void> updateEssayMaterial(EssayMaterial material) async {
    final updatedMaterial = material.copyWith(
      updatedAt: DateTime.now().millisecondsSinceEpoch,
    );
    await _dbService.update(_tableName, updatedMaterial.toMap());
  }

  /// 删除作文素材
  Future<void> deleteEssayMaterial(int id) async {
    await _dbService.delete(_tableName, id);
  }
  
  /// 删除所有作文素材
  Future<bool> deleteAllEssayMaterials() async {
    try {
      await _dbService.clearTable(_tableName);
      return true;
    } catch (e) {
      print('删除所有作文素材失败: $e');
      return false;
    }
  }

  /// 批量添加作文素材
  Future<List<int>> addEssayMaterials(List<EssayMaterial> materials) async {
    final List<int> ids = [];
    for (final material in materials) {
      final id = await addEssayMaterial(material);
      ids.add(id);
    }
    return ids;
  }

  /// 获取作文素材总数
  Future<int> getEssayMaterialCount() async {
    return await _dbService.count(_tableName);
  }

  /// 获取分类列表
  Future<List<String>> getCategories() async {
    final allMaterials = await getAllEssayMaterials();
    final categories = allMaterials
        .map((material) => material.category)
        .where((category) => category.isNotEmpty)
        .toSet()
        .toList();
    categories.sort();
    return categories;
  }

  /// 获取所有标签
  Future<List<String>> getAllTags() async {
    final allMaterials = await getAllEssayMaterials();
    final allTags = <String>{};
    
    for (final material in allMaterials) {
      if (material.tags.isNotEmpty) {
        final tags = material.tags.split(',').map((tag) => tag.trim());
        allTags.addAll(tags);
      }
    }
    
    final tagList = allTags.toList();
    tagList.sort();
    return tagList;
  }

  /// 获取所有来源
  Future<List<String>> getAllSources() async {
    final allMaterials = await getAllEssayMaterials();
    final sources = allMaterials
        .map((material) => material.source)
        .where((source) => source.isNotEmpty)
        .toSet()
        .toList();
    sources.sort();
    return sources;
  }

  /// 获取分类统计
  Future<Map<String, int>> getCategoryStats() async {
    final allMaterials = await getAllEssayMaterials();
    final stats = <String, int>{};
    
    for (final material in allMaterials) {
      if (material.category.isNotEmpty) {
        stats[material.category] = (stats[material.category] ?? 0) + 1;
      }
    }
    
    return stats;
  }

  /// 获取来源统计
  Future<Map<String, int>> getSourceStats() async {
    final allMaterials = await getAllEssayMaterials();
    final stats = <String, int>{};
    
    for (final material in allMaterials) {
      if (material.source.isNotEmpty) {
        stats[material.source] = (stats[material.source] ?? 0) + 1;
      }
    }
    
    return stats;
  }

  /// 清空所有作文素材
  Future<void> clearAllEssayMaterials() async {
    await _dbService.clearTable(_tableName);
  }

  /// 导出作文素材为文本
  Future<String> exportEssayMaterialsToText() async {
    final allMaterials = await getAllEssayMaterials();
    final buffer = StringBuffer();
    
    for (final material in allMaterials) {
      buffer.writeln('标题: ${material.title}');
      buffer.writeln('分类: ${material.category}');
      buffer.writeln('标签: ${material.tags}');
      buffer.writeln('来源: ${material.source}');
      buffer.writeln('创建时间: ${DateTime.fromMillisecondsSinceEpoch(material.createdAt)}');
      buffer.writeln('内容:');
      buffer.writeln(material.content);
      buffer.writeln('${'=' * 50}');
      buffer.writeln();
    }
    
    return buffer.toString();
  }
}